<!-- 营收结算标准  新建编辑查看 -->
<template>
    <div>
        <el-breadcrumb v-if="!viewDetailReceiveId" separator="/" class="bread-title">
            <el-breadcrumb-item :to="{ path: '/revenueSettlement' }">营收结算标准</el-breadcrumb-item>
            <el-breadcrumb-item>{{typeMap[type]}}</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 选择月 年  3.0只保留月 -->
        <div class="chooseType" v-if="nextStep === 0">
            <h3>选择标准规则生效类型</h3>
            <el-radio v-model="selectedTypeValue" label="month">月度</el-radio>
            <el-radio v-model="selectedTypeValue" label="year">年度</el-radio>
            <div class="mt20">
                <el-button @click="returnList">取消</el-button>
                <el-button type="primary" @click="nextStep = 1">下一步</el-button>
            </div>
        </div>
        <!-- 月 -->
        <div v-if="nextStep === 1 && selectedTypeValue === 'month'">

            <el-form v-if="type=== 'view'" size="small" label-width="120px">
                <el-form-item label="提取标准：">营收结算标准</el-form-item>
                <el-form-item label="佣金来源：">{{['项目等级', '开发商类型'][commissionSource -1]}}</el-form-item>
            </el-form>
            <el-form v-else size="small" label-width="120px">
                <el-form-item label="提取标准：">营收结算标准</el-form-item>
                <el-form-item label="佣金来源：">
                    <el-select v-model="commissionSourceFake" placeholder="请选择" @change="changeCommissionSource">
                        <el-option
                                v-for="item in commissionSourceOptions"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item v-if="commissionSource === 2" label="选择开发商：">
                    <el-button @click="chooseDevType">选择开发商</el-button>
                </el-form-item>
                <el-form-item v-else label="选择等级类型：">
                    <el-checkbox-group  style="display: inline-block;" v-model="selectedLevelTypeList">
                        <el-checkbox :disabled="developSettingList[item.id]" v-for="item in levelTypeList" :key="item.id" :label="item.id">
                            {{item.developerName}} - {{item.name}}
                        </el-checkbox>
                    </el-checkbox-group>
                    <!--<el-button size="mini" @click="chooseDevType">选择开发商</el-button>-->
                </el-form-item>
                <el-form-item label="">
                    <div class="mt10" v-for="tag in devTypeTag">
                        <el-tag
                                :key="tag"
                                closable
                                :disable-transitions="true"
                                @close="devTagClose(tag)">
                            {{devTypeListMap[tag].developerName}}
                        </el-tag>
                    </div>
                </el-form-item>
                <el-form-item label="">
                    <el-button type="primary" @click="addDev">添加</el-button>
                </el-form-item>
            </el-form>

            <hr/>


            <div v-for="(item,index) in developSettingList" :key="index" class="devType-item">
                <h3>{{commissionSource === 1 ? (levelTypeListMap[index].developerName + ' - ' +
                    levelTypeListMap[index].name) : (devTypeListMap[index].developerName) }}
                    <el-button v-if="type!=='view'" class="devType-item-del" type="text" @click="delDev(index)">删除
                    </el-button>
                </h3>
                <el-form v-if="type==='view'" size="small" label-width="120px">
                    <el-form-item label="提取规则：">基数*比例</el-form-item>
                    <el-form-item label="计提节点：">{{item.calcNodeList | calNodeFilter}}</el-form-item>
                    <el-form-item label="计提基数：">{{['好生活总收入','好生活平台费'][item.extractBaseNum - 1]}}</el-form-item>
                    <el-form-item label="计提比例：">{{item.calProportion}}%</el-form-item>
                </el-form>
                <el-form v-else size="small" label-width="120px">
                    <el-form-item label="提取规则：">
                        <el-radio v-model="item.extractCategory" :label="2">基数*比例</el-radio>
                    </el-form-item>
                    <el-form-item label="计提节点：">
                        <ul class="calc-node-list">
                            <li v-for="(subItem, subIndex) in item.calcNodeList">
                                <i class="el-icon-circle-close calc-node-close" @click="removeCalcNode(item.calcNodeList, subIndex)"></i>
                                <div>
                                    计提节点：
                                    <el-select size="small" style="width: 120px;" v-model="subItem.calculateNode" placeholder="请选择节点">
                                        <el-option
                                                v-for="option in calcNodeOptions"
                                                :disabled="!!item.calcNodeList.find(calcNodeItem => calcNodeItem.calculateNode === option.value)"
                                                :key="option.value"
                                                :label="option.label"
                                                :value="option.value">
                                        </el-option>
                                    </el-select>
                                </div>
                                <div class="mt20">
                                    计提比例：
                                    <el-input style="width: 100px;" v-model="subItem.calculateProportion" @input="rewireCalcNode(item.calcNodeList, subItem.calculateProportion, subIndex)" size="small" placeholder="请输入内容"></el-input>
                                    %
                                </div>
                            </li>
                            <li class="calc-node-add">
                                <i class="el-icon-circle-plus " @click="addCalcNode(item.calcNodeList)"></i>
                            </li>
                        </ul>
                        <!--<el-select v-model="item.calNode" placeholder="请选择">-->
                        <!--<el-option-->
                        <!--v-for="subItem in calcNodeOptions"-->
                        <!--:key="subItem.value"-->
                        <!--:label="subItem.label"-->
                        <!--:value="subItem.value">-->
                        <!--</el-option>-->
                        <!--</el-select>-->
                    </el-form-item>
                    <el-form-item label="计提基数：">
                        <el-select v-model="item.extractBaseNum" placeholder="请选择">
                            <el-option
                                    v-for="subItem in calcBasicOptions"
                                    :key="subItem.value"
                                    :label="subItem.label"
                                    :value="subItem.value">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="计提比例：">
                        <el-input style="width: 200px;" @input="checkNum(item.calProportion, index)" v-model="item.calProportion" placeholder="请输入内容"></el-input>
                        %
                    </el-form-item>
                </el-form>
            </div>
            <div class="mt30" v-if="type !== 'view'">
                <!--<el-button v-if="type ==='new'" @click="nextStep = 0">上一步</el-button>-->
                <el-button @click="returnList">取消</el-button>
                <el-button type="primary" @click="saveMonth">保存</el-button>
            </div>

        </div>
        <!-- 年 -->
        <!--<div v-else-if="nextStep === 1 && selectedTypeValue === 'year'">

            <div>提取标准：营收结算标准 - 年</div>
            <div class="mt20 mb20">佣金来源：
                <span v-if="type === 'view'">开发商类型</span>
                <el-select v-else v-model="commissionSource" placeholder="请选择">
                    <el-option
                            v-for="item in commissionSourceOptions"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                    </el-option>
                </el-select>
            </div>
            <hr class="mt30 mb30"/>
            <div>提取规则：
                <span v-if="type === 'view'">基数*比例</span>
                <el-radio v-else v-model="yearParams.extractCategory" :label="2">基数*比例</el-radio>
            </div>
            <div class="mt20 mb20">计提节点：
                <span v-if="type === 'view'">认购</span>
                <el-select v-else v-model="yearParams.calNode" placeholder="请选择">
                    <el-option
                            v-for="subItem in calcNodeOptions"
                            :key="subItem.value"
                            :label="subItem.label"
                            :value="subItem.value">
                    </el-option>
                </el-select>
            </div>
            <div class="mt20 mb20">计提基数：
                <span v-if="type === 'view'">好生活总收入</span>
                <el-select v-else v-model="yearParams.extractBaseNum" placeholder="请选择">
                    <el-option
                            v-for="subItem in calcBasicOptions"
                            :key="subItem.value"
                            :label="subItem.label"
                            :value="subItem.value">
                    </el-option>
                </el-select>
            </div>
            <div>计提比例：
                <span v-if="type === 'view'">{{yearParams.calProportion}}</span>
                <el-input v-else style="width: 200px;" @input="checkScale(yearParams.calProportion, 'calProportion')" v-model="yearParams.calProportion" placeholder="请输入内容"></el-input>
                %
            </div>
            <div class="mt20 mb20" v-if="type !== 'view'">
                <el-radio v-model="yearParams.taxNode" :label="1">税前</el-radio>
                <el-radio v-model="yearParams.taxNode" :label="2">税后</el-radio>
            </div>
            <div class="mb30" v-if="yearParams.taxNode === 2">
                <hr class="mt30 mb30"/>
                税后比例：
                <span v-if="type === 'view'">{{yearParams.calProportionAfter}}</span>
                <el-input v-else style="width: 200px;" @input="checkScale(yearParams.calProportionAfter, 'calProportionAfter')" v-model="yearParams.calProportionAfter" placeholder="请输入内容"></el-input>
                %
            </div>
            <div v-if="type !== 'view'">
                <el-button v-if="type ==='new'" @click="nextStep = 0">上一步</el-button>
                <el-button type="primary" @click="saveYear">保存</el-button>
            </div>
        </div>-->
        <el-dialog
                title="选择开发商"
                :visible.sync="devTypeDialogVisible"
                width="550px"
        >
            <el-transfer
                    filterable
                    filter-placeholder="请输入开发商"
                    :titles="['全部开发商', '已选中']"
                    v-model="devType"
                    :data="devTypeList">
            </el-transfer>
            <span slot="footer" class="dialog-footer">
                <el-button @click="devTypeDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="selectDev">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
    import api from '@/api/apiPath'

    export default {
        name: "revenueSettlementHandle",
        data() {
            return {
                type: "new",
                typeMap: {
                    new: '新建',
                    edit: '编辑',
                    view: '查看'
                },
                selectedTypeValue: "month",
                nextStep: 1,

                commissionSource: 2,
                commissionSourceFake: 2, // 切换用
                commissionSourceOptions: [
                    {
                        value: 2,
                        label: '开发商类型'
                    },
                    {
                        value: 1,
                        label: '项目等级'
                    }
                ],
                devTypeDialogVisible: false,
                devTypeList: [],
                devTypeListMap: {},
                levelTypeList: [],
                levelTypeListMap: {},
                selectedLevelTypeList: [],
                devType: [],
                devTypeTag: [],
                calcNodeOptions: [
                    {
                        value: 1,
                        label: '认购'
                    },
                    {
                        value: 2,
                        label: '交易及佣金确认'
                    },
                    {
                        value: 3,
                        label: '回款'
                    },
                    {
                        value: 4,
                        label: '签约'
                    }
                ],
                calcBasicOptions: [
                    {
                        value: 1,
                        label: '好生活总收入'
                    },
                    {
                        value: 2,
                        label: '好生活平台费'
                    }
                ],

                developSettingList: {},
                //  year
                yearParams: {
                    extractCategory: 2,
                    calNode: 1,
                    extractBaseNum: 2,
                    taxNode: 1,
                    calProportion: "",
                    calProportionAfter: ""
                }
            }
        },
        created() {
            this.getAllDevList();
            this.getAllProjectLevel();
            this.type = this.$route.query.type || 'new';
            this.selectedTypeValue = this.$route.query.dateType || 'month';
            if (this.type !== 'new') {
                this.nextStep = 1;
                this.getSingleRS(this.selectedTypeValue, this.$route.query.id)
            }
        },

        props: ['viewDetailReceiveId'],
        watch: {
            viewDetailReceiveId: {
                handler(id) {
                    if (id) {
                        setTimeout(() => {
                            this.type = 'view';
                        }, 30)
                        this.nextStep = 1;
                        this.getSingleRS(this.selectedTypeValue, id)
                    }
                },
                immediate: true
            }
        },

        filters: {
            calNodeFilter(list) {
                let arr = [];
                list.forEach((item) => {
                    arr.push(item.calculateNodeName + '-' + item.calculateProportion + '%')
                });
                return arr.join(';')
            }
        },
        methods: {
            // 3.0
            changeCommissionSource() {
                if (Object.keys(this.developSettingList).length) {
                    this.$confirm('切换后设置将更新，是否切换?', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        this.commissionSource = this.commissionSourceFake;
                        this.selectedLevelTypeList = []
                        this.devTypeTag = []
                        this.developSettingList = {};
                    }).catch(() => {
                        this.commissionSourceFake = [2, 1][this.commissionSourceFake - 1]
                    });
                } else {
                    this.selectedLevelTypeList = []
                    this.devTypeTag = []
                    this.commissionSource = this.commissionSourceFake;
                }
            },

            formatTwoDecimal(value, maxNumber, isIncludeMax) {
                value = value.replace(/[^\d.]/g, '');
                value = value.replace(/\.{2,}/g, ".");
                value = value.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
                value = value.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3');
                if (value.indexOf('.') < 0 && value != '') {
                    value = parseInt(value);
                }
                // 设置最大限制
                if (maxNumber) {
                    const bool = isIncludeMax ? +value >= maxNumber : +value > maxNumber;
                    if (bool) {
                        let valueString = String(value)
                        value = valueString.slice(0, valueString.length - 1)
                    }
                }
                return value
            },
            rewireCalcNode(list, value, index) {
                this.$set(list[index], 'calculateProportion', this.formatTwoDecimal(value, 100))
            },
            calcNodeSum(calcNodeList) {
                let calcSum = 0;
                for (let i = 0; i < calcNodeList.length; i++) {
                    let item = calcNodeList[i]
                    if (!item.calculateNode) {
                        this.$message.warning('有计提节点未选择');
                        return 0
                    }
                    if (item.calculateProportion === '') {
                        this.$message.warning('有计提比例未设置');
                        return 0
                    }
                    if (Number(item.calculateProportion) === 0) {
                        this.$message.warning('计提比例不能设置为0');
                        return 0
                    }
                    calcSum += Number(item.calculateProportion)
                }
                return calcSum
            },

            addCalcNode(calcNodeList) {
                // 先判断长度
                if (calcNodeList.length >= this.calcNodeOptions.length) {
                    this.$message.warning("不能再添加计提节点了")
                    return false;
                }
                const calcNodeSum = this.calcNodeSum(calcNodeList)
                // calcNodeSum=0 直接拦截
                if (calcNodeSum === 0) {
                    return false
                }
                if (calcNodeSum >= 100) {
                    this.$message.warning("计提节点总和不能大于100%")
                    return false;
                } else {
                    calcNodeList.push({
                        calculateNode: "",
                        calculateProportion: ''
                    })
                }
            },
            removeCalcNode(calcNodeList, index) {
                if (calcNodeList.length <= 1) {
                    this.$message.warning("请至少设置一个计提节点")
                    return false
                }
                calcNodeList.splice(index, 1)
            },


            returnList() {
                this.$router.push({path: "./revenueSettlement"})
            },
            // checkScale(value, field) {
            //     value = this.formatTwoDecimal(value, 100);
            //     setTimeout(() => {
            //         this.$set(this.yearParams, field, value)
            //     }, 30)
            // },

            checkNum(value, index) {
                value = this.formatTwoDecimal(value, 100);
                this.$set(this.developSettingList[index], 'calProportion', value)
            },
            chooseDevType() {
                this.devTypeDialogVisible = true;
                this.devTypeList.forEach((item, index) => {
                    this.$set(this.devTypeList[index], 'disabled', !!this.developSettingList[item.key] || this.devTypeTag.indexOf(item.key) > -1)
                })
            },
            selectDev() {
                if (this.devType.length > 0) {
                    this.devTypeDialogVisible = false;
                    this.devTypeTag.push(...this.devType);
                    this.devType = [];
                } else {
                    this.$message({
                        message: "请选择开发商！",
                        type: 'warning'
                    });
                    return false;
                }
            },
            devTagClose(tag) {
                this.devTypeTag.splice(this.devTypeTag.indexOf(tag), 1)
            },
            addDev() {
                // 1项目等级   2开发商类型
                const waitAddList = this.commissionSource === 1 ? this.selectedLevelTypeList : this.devTypeTag;
                const waitMapList = this.commissionSource === 1 ? this.levelTypeListMap : this.devTypeListMap;
                const len = waitAddList.length;
                if (len) {
                    let developSettingList = JSON.parse(JSON.stringify(this.developSettingList));
                    for (let i = 0; i < len; i++) {
                        const item = waitAddList[i];
                        const itemData = waitMapList[item];
                        if (developSettingList[item]) {
                            const nameTips = this.commissionSource === 1 ? (itemData.developerName + ' - ' + itemData.name) : itemData.developerName
                            this.$confirm(nameTips + ' 已添加', '提示', {
                                confirmButtonText: '确定',
                                showCancelButton: false,
                                type: 'warning',
                                center: true
                            })
                            return false;
                        }
                        developSettingList[item] = {
                            developerId: itemData.developerId || itemData.id,
                            developerName: itemData.developerName,
                            code: itemData.code ? itemData.id : undefined,
                            name: itemData.name,

                            extractCategory: 2,
                            calcNodeList: [{
                                calculateNode: 1,
                                calculateProportion: ''
                            }],
                            extractBaseNum: 1,
                            calProportion: ""
                        }
                    }
                    this.devTypeTag = [];
                    this.selectedLevelTypeList = [];
                    this.developSettingList = JSON.parse(JSON.stringify(developSettingList));
                } else {
                    this.$message({
                        message: `请选择${['等级类型', '开发商'][this.commissionSource - 1]}！`,
                        type: 'warning'
                    });
                    return false;
                }
            },
            delDev(id) {
                this.$delete(this.developSettingList, id)
            },
            getAllDevList() {
                this.axios.post(api.getAllDevList, {}).then((res) => {
                    let devTypeList = [];
                    let devTypeListMap = [];
                    res.data.data.forEach((item) => {
                        devTypeList.push({
                            label: item.developerName,
                            key: item.id
                        })
                        devTypeListMap[item.id] = item;
                    })
                    this.devTypeList = devTypeList;
                    this.devTypeListMap = devTypeListMap;
                })
            },
            getAllProjectLevel() {
                this.axios.post(api.getAllProjectLevel, {}).then((res) => {
                    this.levelTypeList = res.data.data;
                    let levelTypeListMap = {};
                    this.levelTypeList.forEach((item) => {
                        levelTypeListMap[item.id] = item
                    })
                    this.levelTypeListMap = levelTypeListMap;
                })
            },
            saveMonth() {
                let developSettingList = []
                if (Object.keys(this.developSettingList).length) {
                    for (let key in this.developSettingList) {
                        let item = this.developSettingList[key]
                        const fullName = this.commissionSource === 1 ? (item.developerName + ' - ' + item.name) : item.developerName

                        //console.log(item);
                        const calcNodeSum = this.calcNodeSum(item.calcNodeList);
                        if (calcNodeSum === 0) {
                            return false
                        }
                        if (calcNodeSum !== 100) {
                            this.$message.warning(fullName + ' - 计提比例总和不等于100%');
                            return false
                        }
                        if (item.calProportion) {
                            if (+item.calProportion > 0 && +item.calProportion < 100) {
                                developSettingList.push({
                                    projectLevelId: item.code || item.projectLevelId,
                                    projectLevelName: item.name || item.projectLevelName,
                                    extractBaseNum: item.extractBaseNum,
                                    calculateNodeList: item.calcNodeList,
                                    calculateProportion: item.calProportion,
                                    developerId: item.developerId,
                                    developerName: item.developerName,
                                    extractCategory: +item.extractCategory,
                                })
                            } else {
                                this.$message({
                                    message: fullName + " 计提比例必须大于0小于100！",
                                    type: 'warning'
                                });
                                return false
                            }
                        } else {
                            this.$message({
                                message: fullName + " 计提比例不能为0或空！",
                                type: 'warning'
                            });
                            return false
                        }
                    }
                } else {
                    this.$message({
                        message: '请选择开发商或项目等级',
                        type: 'warning'
                    });
                    return false
                }
                let params = {
                    extractStandard: 2,
                    //ruleEffect: 1,
                    source: this.commissionSource,
                    developSettingList: developSettingList
                };
                //console.log(params);
                this.axios.post(api.createRevenueStandardByMonth, params).then((res) => {
                    if (res.data.code === 200) {
                        this.$message({
                            message: this.typeMap[this.type] + "成功",
                            type: 'success'
                        });
                        this.returnList();
                    }
                })
            },
            saveYear() {
                let params = {
                    ...this.yearParams,
                    extractStandard: 3,
                    ruleEffect: 2,
                    source: 1
                }

                if (!params.calProportion) {
                    this.$message({
                        message: '计提比例不能为0或空！',
                        type: 'warning'
                    });
                    return false;
                }
                if (+params.calProportion < 0 || +params.calProportion >= 100) {
                    this.$message({
                        message: '计提比例必须大于0小于100！',
                        type: 'warning'
                    });
                    return false;
                }

                if (params.taxNode === 2) {
                    if (!params.calProportionAfter) {
                        this.$message({
                            message: '税后比例不能为0或空！',
                            type: 'warning'
                        });
                        return false;
                    }
                    if (+params.calProportionAfter < 0 || +params.calProportionAfter >= 100) {
                        this.$message({
                            message: '税后比例必须大于0小于100！',
                            type: 'warning'
                        });
                        return false;
                    }
                }
                this.axios.post(api.createRevenueStandardByYear, params).then((res) => {
                    if (res.data.code === 200) {
                        this.$message({
                            message: this.typeMap[this.type] + "成功",
                            type: 'success'
                        });
                        this.returnList();
                    }
                })
            },
            getSingleRS(type, id) {
                if (type === 'month') {
                    this.axios.post(api.viewRevenueStandardByMonth, {
                        standardId: id
                    }).then((res) => {
                        const data = res.data.data
                        this.commissionSourceFake = data.source;
                        this.commissionSource = data.source;
                        let developSettingList = {};
                        data.standardRelList.forEach((item) => {
                            developSettingList[item.projectLevelId || item.developerId] = {
                                extractBaseNum: item.extractBaseNum,
                                extractCategory: item.extractCategory,
                                calcNodeList: item.calculateNodeList,
                                calProportion: item.calProportion,
                                developerId: item.developerId,
                                developerName: item.developerName,

                                projectLevelId: item.projectLevelId,
                                projectLevelName: item.projectLevelName
                            }
                        })
                        this.developSettingList = developSettingList;
                    })
                } else {
                    this.axios.post(api.viewRevenueStandardByYear, {
                        standardId: id
                    }).then((res) => {
                        let data = res.data.data
                        this.yearParams = {
                            extractCategory: data.extractCategory,
                            calNode: data.calNode,
                            extractBaseNum: data.extractBaseNum,
                            taxNode: data.taxNode,
                            calProportion: data.calProportion,
                            calProportionAfter: data.calProportionAfter
                        }
                    })
                }
            }
        },
        components: {},
        computed: {}
    }
</script>

<style scoped lang="stylus">
    .devType-item {
        position: relative;
        .devType-item-del {
            margin-left: 30px;
            color: red;
        }
    }

    // 3.0
    .calc-node-list {
        display: inline-block;
        position: relative;
        vertical-align: middle;
        margin: 0;
        padding: 0;
        li {
            position: relative;
            border: 1px solid #ccc;
            margin: 0 30px 30px 0;
            border-radius: 4px;
            padding: 15px;
            display: inline-block;
        }
        .calc-node-close {
            background-color: #fff;
            position: absolute;
            right: -15px;
            top: -15px;
            font-size: 30px;
            cursor: pointer;
        }
        .calc-node-add {
            margin-top: -30px;
            padding: 0;
            border: none;
            vertical-align: middle;
            font-size: 30px;
            cursor: pointer;
        }
    }
</style>
